<?php


namespace app\cms\model\saas;


use app\cms\community\lib\QueryModel;
use app\cms\dto\saas\saasClientInfo;
use iflow\Response;
use iflow\Utils\basicTools;
use think\model\relation\HasOne;

class saasClientModel extends QueryModel
{
    protected $table = 'saas_client_table';
    const isSaasModel = true;

    public function hasSaasDb(): HasOne
    {
        return $this->hasOne(
            saasClientDbModel::class, 'saas_id', 'saas_id'
        );
    }

    public function hasSaasServer(): HasOne
    {
        return $this->hasOne(
            saasClientServerModel::class,
            'server_id',
            'server_id'
        );
    }

    /**
     * 获取saas服务信息
     * @param int $uid
     * @param int $saas_id
     * @return array
     */
    public function getSaasInfo(int $uid = 0, int $saas_id = 0): array
    {
        $where = [
            'saas_client_table.saas_domain' => request() -> getHeader('host')
        ];
        if ($uid > 0) $where['saas_client_table.uid'] = $uid;

        if ($saas_id > 0) {
            $where['saas_id'] = $saas_id;
            unset($where['saas_client_table.saas_domain']);
        }

        $info = $this->withJoin([
            // 获取数据库
            'hasSaasDb' => [
                'db_ip' => 'db_ip',
                'db_port' => 'db_port',
                'db_user' => 'db_user',
                'db_password' => 'db_password',
                'db_name' => 'db_name',
                'db_capacity' => 'db_capacity'
            ],
            // 获取服务器地址
            'hasSaasServer' => [
                'server_name' => 'server_name',
                'server_ip' => 'server_ip'
            ]
        ], 'LEFT') -> where($where) -> findOrEmpty();
        return $info -> isEmpty() ? [] : $info -> toArray();
    }

    /**
     * 保存信息
     * @param saasClientInfo $saasClientInfo
     * @return Response
     */
    public function saveSaasClient(saasClientInfo $saasClientInfo): Response
    {
        $info = (new basicTools()) -> objectToArray($saasClientInfo);
        $info['uid'] = $saasClientInfo -> getUid();
        return $this->createData($info);
    }

    /**
     * 更新Saas服务
     * @param saasClientInfo $saasClientInfo
     * @return Response
     */
    public function updateSaasClient(saasClientInfo $saasClientInfo): Response
    {
        return $this->updateInfo([
            'saas_domain' => $saasClientInfo -> saas_domain,
            'saas_as_domain' => $saasClientInfo -> saas_as_domain,
            'lease_renewal_time' => $saasClientInfo -> lease_renewal_time,
            'lease_renewal_end_time' => $saasClientInfo -> lease_renewal_end_time,
        ], [
            'uid' => $saasClientInfo -> getUid(),
            'saas_id' => $saasClientInfo -> saas_id
        ]);
    }

    /**
     * 获取SAAS 客户端列表
     * @param string $saas_domain
     * @param string $saas_as_domain
     * @param int $uid
     * @param int $status
     * @return Response
     */
    public function getSaasClientList(
        string $saas_domain = '',
        string $saas_as_domain = '',
        int $uid = 0,
        int $status = -1
    ): Response {
        $query = $this->withJoin([
            // 数据库地址
            'hasSaasDb' => [
                'db_ip' => 'db_ip',
                'db_port' => 'db_port',
                'db_user' => 'db_user',
                'db_password' => 'db_password',
                'db_name' => 'db_name',
                'db_capacity' => 'db_capacity'
            ],
            // 服务器地址
            'hasSaasServer' => [
                'server_name' => 'server_name',
                'server_ip' => 'server_ip'
            ]
        ], 'LEFT');

        if ($saas_as_domain !== '') {
            $query -> whereLike('saas_as_domain', "%{$saas_as_domain}%");
        }

        if ($saas_domain !== '') {
            $query -> whereLike('saas_domain', "%{$saas_domain}%");
        }

        if ($uid > 0) {
            $query -> where('uid', '=', $uid);
        }

        // 获取状态
        if ($status > -1) {
            match ($status) {
                // 已过期
                0 => $query -> where('lease_renewal_end_time', '>', time()),
                // 正常
                1 => $query -> where('status', '=', 1),
                // 未生效
                2 => $query -> where('lease_renewal_time', '<', time()),
                default => ''
            };
        }

        return $this->paginateQuery($query);
    }

    public function getSaasServerInfoByDomain(string $domain): array
    {
        $account = $this->withJoin([
            // 数据库地址
            'hasSaasDb' => [
                'db_ip' => 'db_ip',
                'db_port' => 'db_port',
                'db_user' => 'db_user',
                'db_password' => 'db_password',
                'db_name' => 'db_name',
                'db_capacity' => 'db_capacity'
            ],
            // 服务器地址
            'hasSaasServer' => [
                'server_name' => 'server_name',
                'server_ip' => 'server_ip'
            ]
        ], 'LEFT')
        -> where([
            'saas_domain' => $domain
        ]) -> find() ?-> toArray();

        return $account ?: [];
    }
}